package com.wlf.server.common.xss;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * xss过滤包装类
 */
@Slf4j
public class XssRequestWrapper extends HttpServletRequestWrapper {

    public XssRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        String strHeader = super.getHeader(name);
        if (StrUtil.isEmpty(strHeader)) {
            return strHeader;

        }
        return HtmlUtils.htmlEscape(super.getHeader(name), "UTF-8");
    }

    @Override
    public String getParameter(String name) {
        String strParameter = super.getParameter(name);
        if (StrUtil.isEmpty(strParameter)) {
            return strParameter;
        }
        return HtmlUtils.htmlEscape(super.getParameter(name), "UTF-8");
    }


    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null) {
            return null;
        }
        int length = values.length;
        String[] escapeValues = new String[length];
        for (int i = 0; i < length; i++) {
            //过滤一切可能的xss攻击字符串
            escapeValues[i] = HtmlUtils.htmlEscape(values[i], "UTF-8").trim();
        }
        return escapeValues;
    }
}
